/**
 * The MIT License (MIT)
 * 手写板/签字版
 * @author 透笔度
 * @开源中国 https://my.oschina.net/tbd/blog
 * @码云 https://gitee.com/dgx
 */

const towxImg = require('../../../utils/towxImg');
var context = null;// 使用 wx.createContext 获取绘图上下文 context
var isButtonDown = false;//是否在绘制中
var arrx = [];//动作横坐标
var arry = [];//动作纵坐标
var arrz = [];//总做状态，标识按下到抬起的一个组合
var canvasw = 0;//画布宽度
var canvash = 0;//画布高度
// pages/shouxieban/shouxieban.js
Page({
  /**
 * 页面的初始数据
 */
  data: {
    //canvas宽高
    canvasw: 0,
    canvash: 0,
    //canvas生成的图片路径
    canvasimgsrc: "",
    article: ''
  },
  //画布初始化执行
  startCanvas: function () {
    var that = this;
    //创建canvas
    this.initCanvas();
    //获取系统信息
    wx.getSystemInfo({
      success: function (res) {
        canvasw = res.windowWidth - 0;//设备宽度
        canvash = canvasw;
        that.setData({ 'canvasw': canvasw });
        that.setData({ 'canvash': canvash });
      }
    });

  },
  //初始化函数
  initCanvas: function () {
    // 使用 wx.createContext 获取绘图上下文 context
    context = wx.createCanvasContext('canvas');
    context.beginPath()
    context.setStrokeStyle('#000000');
    context.setLineWidth(4);
    context.setLineCap('round');
    context.setLineJoin('round');
  },
  //事件监听
  canvasIdErrorCallback: function (e) {
    console.error(e.detail.errMsg)
  },
  canvasStart: function (event) {
    isButtonDown = true;
    arrz.push(0);
    arrx.push(event.changedTouches[0].x);
    arry.push(event.changedTouches[0].y);

  },
  canvasMove: function (event) {
    if (isButtonDown) {
      arrz.push(1);
      arrx.push(event.changedTouches[0].x);
      arry.push(event.changedTouches[0].y);

    };

    for (var i = 0; i < arrx.length; i++) {
      if (arrz[i] == 0) {
        context.moveTo(arrx[i], arry[i])
      } else {
        context.lineTo(arrx[i], arry[i])
      };

    };
    context.clearRect(0, 0, canvasw, canvash);

    context.setStrokeStyle('#000000');
    context.setLineWidth(4);
    context.setLineCap('round');
    context.setLineJoin('round');
    context.stroke();

    context.draw(false);
  },
  canvasEnd: function (event) {
    isButtonDown = false;
  },
  //清除画布
  cleardraw: function () {
    //清除画布
    arrx = [];
    arry = [];
    arrz = [];
    context.clearRect(0, 0, canvasw, canvash);
    context.draw(true);
  },
  //提交签名内容
  setSign: function () {
    var that = this;
    if (arrx.length == 0) {
      wx.showModal({
        title: '提示',
        content: '签名内容不能为空！',
        showCancel: false
      });
      return false;
    };
    console.log("不是空的，canvas即将生成图片")
    //生成图片
    wx.canvasToTempFilePath({
      canvasId: 'canvas',
      success: function (res) {
        console.log("canvas可以生成图片")
        console.log(res.tempFilePath, 'canvas图片地址');
        that.setData({ canvasimgsrc: res.tempFilePath })
        //code 比如上传操作

      },
      fail: function () {
        console.log("canvas不可以生成图片")
        wx.showModal({
          title: '提示',
          content: '微信当前版本不支持，请更新到最新版本！',
          showCancel: false
        });
      },
      complete: function () { }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //画布初始化执行
    this.startCanvas();

    let code = '```\n<view class="container my-page">\n  <canvas style="width: {{canvasw}}px; height: {{canvash}}px" class="canvas" id="canvas" canvas-id="canvas" disable-scroll="true" bindtouchstart="canvasStart" bindtouchmove="canvasMove" bindtouchend="canvasEnd" touchcancel="canvasEnd" binderror="canvasIdErrorCallback"></canvas>\n  <view class="btns canvaspd">\n    <button bindtap="cleardraw">清除签名</button>\n    <button bindtap="setSign">确定</button>\n  </view>\n  <image src="{{canvasimgsrc}}" mode="widthFix" style="width: 100vw;"></image>\n</view>\n```\n\n```\nvar context = null;// 使用 wx.createContext 获取绘图上下文 context\nvar isButtonDown = false;\nvar arrx = [];\nvar arry = [];\nvar arrz = [];\nvar canvasw = 0;\nvar canvash = 0;\n//获取应用实例\nconst app = getApp()\n//注册页面\nPage({\n  /**\n  * 页面的初始数据\n  */\n  data: {\n    //canvas宽高\n    canvasw: 0,\n    canvash: 0,\n    canvasimgsrc: ""\n  },\n  //画布初始化执行\n  startCanvas: function () {\n    var that = this;\n    //创建canvas\n    this.initCanvas();\n    //获取系统信息\n    wx.getSystemInfo({\n      success: function (res) {\n        canvasw = res.windowWidth - 0;//设备宽度\n        canvash = canvasw;\n        that.setData({ "canvasw": canvasw });\n        that.setData({ "canvash": canvash });\n      }\n    });\n  },\n  initCanvas: function () {\n    // 使用 wx.createContext 获取绘图上下文 context\n    context = wx.createCanvasContext("canvas");\n    context.beginPath()\n    context.setStrokeStyle("#000000");\n    context.setLineWidth(4);\n    context.setLineCap("round");\n    context.setLineJoin("round");\n  },\n  canvasIdErrorCallback: function (e) {\n    console.error(e.detail.errMsg)\n  },\n  canvasStart: function (event) {\n    isButtonDown = true;\n    arrz.push(0);\n    arrx.push(event.changedTouches[0].x);\n    arry.push(event.changedTouches[0].y);\n  },\n  canvasMove: function (event) {\n    if (isButtonDown) {\n      arrz.push(1);\n      arrx.push(event.changedTouches[0].x);\n      arry.push(event.changedTouches[0].y);\n    };\n    for (var i = 0; i < arrx.length; i++) {\n      if (arrz[i] == 0) {\n        context.moveTo(arrx[i], arry[i])\n      } else {\n        context.lineTo(arrx[i], arry[i])\n      };\n    };\n    context.clearRect(0, 0, canvasw, canvash);\n    context.setStrokeStyle("#000000");\n    context.setLineWidth(4);\n    context.setLineCap("round");\n    context.setLineJoin("round");\n    context.stroke();\n    context.draw(false);\n  },\n  canvasEnd: function (event) {\n    isButtonDown = false;\n  },\n  cleardraw: function () {\n    //清除画布\n    arrx = [];\n    arry = [];\n    arrz = [];\n    context.clearRect(0, 0, canvasw, canvash);\n    context.draw(true);\n  },\n  setSign: function () {\n    var that = this;\n    if (arrx.length == 0) {\n      wx.showModal({\n        title: "提示",\n        content: "签名内容不能为空！",\n        showCancel: false\n      });\n      return false;\n    };\n    console.log("不是空的，canvas即将生成图片")\n    //生成图片\n    wx.canvasToTempFilePath({\n      canvasId: "canvas",\n      success: function (res) {\n        console.log("canvas可以生成图片")\n        console.log(res.tempFilePath, "签章canvas图片地址");\n        that.setData({ canvasimgsrc: res.tempFilePath })\n        \n        // 上传\n      },\n      fail: function () {\n        console.log("canvas不可以生成图片")\n        wx.showModal({\n          title: "提示",\n          content: "微信当前版本不支持，请更新到最新版本！",\n          showCancel: false\n        });\n      },\n      complete: function () {\n      }\n    })\n  },\n  /**\n   * 生命周期函数--监听页面加载\n   */\n  onLoad: function (options) {\n    //画布初始化执行\n    this.startCanvas();\n    \n  },\n  /**\n   * 生命周期函数--监听页面初次渲染完成\n   */\n  onReady: function () {\n  },\n  /**\n   * 生命周期函数--监听页面显示\n   */\n  onShow: function () {\n    //移除画布内容\n    this.cleardraw();\n    \n  },\n})\n```\n\n';

    let article = towxImg.dealWithRichText(code);
    this.setData({ article });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    //移除画布内容
    this.cleardraw();


  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    // 监听用户下拉动作
    wx.stopPullDownRefresh();//停止当前页面下拉刷新。
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})
